/* eslint-disable unused-imports/no-unused-vars */
import type { ResumeAddOrUpdateRequest, ResumeDetail, ResumeListItem, ResumeListQuery } from "@/pages/internship/resume/apis/type"
import { ElMessage } from "element-plus"
import { defineStore } from "pinia"
import { reactive, ref } from "vue"
import { addResumeApi, deleteResumeApi, generateResumePdfApi, getResumeDetailApi, getUserResumesApi, updateResumeApi } from "@/pages/internship/resume/apis"
import { pinia } from "@/pinia"
import { useUserStore } from "./user"

// 简单的对象哈希函数，用于比较表单数据是否变化
function createFormHash(form: ResumeAddOrUpdateRequest): string {
  const contentToHash = {
    resumeName: form.resumeName,
    skills: form.skills.map(s => ({ skillName: s.skillName, proficiency: s.proficiency, description: s.description })),
    internExperiences: form.internExperiences.map(e => ({
      company: e.company,
      position: e.position,
      startDate: e.startDate,
      endDate: e.endDate,
      content: e.content
    })),
    languages: form.languages.map(l => ({ language: l.language, level: l.level, score: l.score })),
    awards: form.awards.map(a => ({ name: a.name, issuer: a.issuer, getDate: a.getDate })),
    otherInfo: form.otherInfo
  }

  // 序列化并生成简单哈希
  return JSON.stringify(contentToHash).split("").reduce((hash, char) => {
    const h = ((hash << 5) - hash) + char.charCodeAt(0)
    return h & h
  }, 0).toString()
}

export const useResumeStore = defineStore("resume", () => {
  // 列表与分页状态
  const loading = ref(false)
  const resumeList = ref<ResumeListItem[]>([])
  const total = ref(0)
  const queryParams = reactive<ResumeListQuery>({
    keyword: "",
    userId: 0,
    page: 1,
    size: 10
  })
  const currentDetail = ref<ResumeDetail | null>(null)

  // PDF缓存相关状态
  const cachedPdfInfo = ref<{
    pdfUrl: string
    formHash: string
    timestamp: number
  } | null>(null)

  // 表单数据状态 - 用于简历添加和编辑
  const formData = reactive<ResumeAddOrUpdateRequest>({
    userId: 0,
    resumeName: "",
    isDefault: 0,
    skills: [],
    internExperiences: [],
    languages: [],
    awards: [],
    otherInfo: "",
    resumePdfUrl: "",
    status: 59
  })

  // 移除步骤管理状态，已移至AddResume.vue组件中

  // 获取用户的所有简历
  async function fetchUserResumes(reset = true) {
    if (loading.value) return
    loading.value = true

    try {
      const userStore = useUserStore()
      // 确保设置了当前用户ID
      if (userStore.userInfo?.userId) {
        queryParams.userId = userStore.userInfo.userId
      }

      if (reset) {
        resumeList.value = []
        total.value = 0
        queryParams.page = 1
      }

      let pageData: ResumeListItem[] = []
      let pageTotal = total.value

      const response = await getUserResumesApi({ ...queryParams })
      if (response && response.data && response.data.records) {
        pageData = response.data.records
        pageTotal = response.data.total
      }

      // 确保Vue正确追踪数组变化的方式更新列表
      if (reset) {
        // 重置模式：使用新数组完全替换
        resumeList.value = [...pageData]
      } else {
        // 追加模式：使用splice确保响应式更新
        const startIndex = resumeList.value.length
        resumeList.value.splice(startIndex, 0, ...pageData)
      }
      total.value = pageTotal

      return resumeList.value
    } catch (error) {
      console.error("获取简历列表失败:", error)
      // 错误时使用空列表
      if (reset) {
        resumeList.value = []
      }
      total.value = 0
      return []
    } finally {
      loading.value = false
    }
  }

  // 加载更多数据
  async function loadMore() {
    if (loading.value) return
    if (resumeList.value.length >= total.value) return
    queryParams.page += 1
    await fetchUserResumes(false)
  }

  // 获取简历详情
  async function fetchResumeDetail(resumeId: number) {
    if (!resumeId || typeof resumeId !== "number") {
      console.warn("无效的简历ID:", resumeId)
      return
    }

    loading.value = true
    try {
      const res = await getResumeDetailApi(resumeId)
      // 检查响应数据
      if (res && res.data) {
        currentDetail.value = res.data
      } else {
        currentDetail.value = null
      }
    } catch (error) {
      console.error("获取简历详情失败:", error)
      currentDetail.value = null
    } finally {
      loading.value = false
    }
  }
  // 添加简历
  async function createResume(data?: ResumeAddOrUpdateRequest) {
    try {
      const submitData = data || filterEmptyData(formData)

      // 确保提交数据有效
      if (!submitData.resumeName || submitData.resumeName.trim() === "") {
        console.error("简历名称不能为空")
        return false
      }

      await addResumeApi(submitData)

      // 重新获取简历列表，确保新添加的简历显示出来
      await fetchUserResumes(true)

      ElMessage.success("添加简历成功")
      return true
    } catch (error) {
      console.error("创建简历失败:", error)
      ElMessage.error("添加简历失败")
      return false
    }
  }

  // 初始化表单数据
  function initFormData() {
    resetFormData()
    addSkill()
    addInternExperience()
    addLanguage()
    addAward()
  }

  // 重置表单数据
  function resetFormData() {
    formData.userId = 0
    formData.resumeName = ""
    formData.isDefault = 0
    formData.skills = []
    formData.internExperiences = []
    formData.languages = []
    formData.awards = []
    formData.otherInfo = ""
    formData.resumePdfUrl = ""
    formData.status = 59

    // 清除PDF缓存，因为表单已重置
    cachedPdfInfo.value = null
  }

  // 过滤空数据
  function filterEmptyData(data: ResumeAddOrUpdateRequest): ResumeAddOrUpdateRequest {
    return {
      ...data,
      skills: data.skills.filter(skill => skill.skillName.trim() !== ""),
      internExperiences: data.internExperiences.filter(exp => exp.company.trim() !== ""),
      languages: data.languages.filter(lang => lang.language.trim() !== ""),
      awards: data.awards.filter(award => award.name.trim() !== "")
    }
  }

  // 添加新的技能项
  function addSkill() {
    formData.skills.push({ skillName: "", proficiency: "", description: "" })
  }

  // 删除技能项
  function removeSkill(index: number): boolean {
    if (formData.skills.length > 1) {
      formData.skills.splice(index, 1)
      return true
    } else {
      ElMessage.warning("至少保留一项技能")
      return false
    }
  }

  // 添加新的实习经历
  function addInternExperience() {
    formData.internExperiences.push({
      company: "",
      position: "",
      startDate: "",
      endDate: "",
      content: ""
    })
  }

  // 删除实习经历
  function removeInternExperience(index: number): boolean {
    if (formData.internExperiences.length > 1) {
      formData.internExperiences.splice(index, 1)
      return true
    } else {
      ElMessage.warning("至少保留一项实习经历")
      return false
    }
  }

  // 添加新的语言能力
  function addLanguage() {
    formData.languages.push({ language: "", level: "", score: "" })
  }

  // 删除语言能力
  function removeLanguage(index: number): boolean {
    if (formData.languages.length > 1) {
      formData.languages.splice(index, 1)
      return true
    } else {
      ElMessage.warning("至少保留一项语言能力")
      return false
    }
  }

  // 添加新的获奖情况
  function addAward() {
    formData.awards.push({ name: "", issuer: "", getDate: "" })
  }

  // 删除获奖情况
  function removeAward(index: number): boolean {
    if (formData.awards.length > 1) {
      formData.awards.splice(index, 1)
      return true
    } else {
      ElMessage.warning("至少保留一项获奖情况")
      return false
    }
  }

  // 移除步骤导航方法，已移至AddResume.vue组件中

  // 设置当前用户ID到表单
  function setCurrentUserId(userId: number) {
    formData.userId = userId
  }

  // 更新简历
  async function updateResume(resumeId: number, data: ResumeAddOrUpdateRequest) {
    try {
      await updateResumeApi(resumeId, data)
      ElMessage.success("更新简历成功")
      return true
    } catch (error) {
      ElMessage.error("更新简历失败")
      return false
    }
  }

  // 删除简历
  async function removeResume(resumeId: number) {
    try {
      await deleteResumeApi(resumeId)
      ElMessage.success("删除简历成功")
      // 重新获取列表
      await fetchUserResumes(true)
      return true
    } catch (error) {
      console.error("删除简历失败:", error)
      ElMessage.error("删除简历失败")
      return false
    }
  }

  // 更新查询参数
  function updateQueryParams(params: Partial<ResumeListQuery>) {
    Object.assign(queryParams, params)
  }

  // 重置查询参数
  function resetQueryParams() {
    queryParams.keyword = ""
    queryParams.userId = 0
    queryParams.page = 1
    queryParams.size = 10
  }

  // 重置当前详情
  function resetCurrentDetail() {
    currentDetail.value = null
  }

  // 生成简历PDF
  async function generateResumePdf(): Promise<string | null> {
    try {
      // 检查表单数据是否有效
      if (!formData.resumeName || formData.resumeName.trim() === "") {
        ElMessage.warning("简历名称不能为空")
        return null
      }

      // 生成当前表单的哈希值
      const currentFormHash = createFormHash(formData)

      // 检查是否有缓存的PDF且表单内容没有变化
      if (cachedPdfInfo.value && cachedPdfInfo.value.formHash === currentFormHash) {
        // 如果有缓存且表单未变，直接返回缓存的PDF URL
        console.log("使用缓存的PDF")
        return cachedPdfInfo.value.pdfUrl
      }

      loading.value = true

      // 准备发送给API的数据
      const data = {
        userId: formData.userId || useUserStore().userInfo?.userId || 0,
        resumeName: formData.resumeName,
        isDefault: formData.isDefault,
        skills: formData.skills,
        internExperiences: formData.internExperiences,
        languages: formData.languages,
        awards: formData.awards,
        otherInfo: formData.otherInfo,
        resumePdfUrl: formData.resumePdfUrl,
        status: formData.status
      }

      const response = await generateResumePdfApi(data)

      if (response && response.data) {
        // 更新缓存信息
        cachedPdfInfo.value = {
          pdfUrl: response.data,
          formHash: currentFormHash,
          timestamp: Date.now()
        }

        // 同时更新formData中的PDF URL
        formData.resumePdfUrl = response.data

        // 如果有当前详情，也更新详情中的PDF信息
        if (currentDetail.value) {
          currentDetail.value.resumePdfUrl = response.data
          currentDetail.value.resumePdfGenerateTime = new Date().toISOString()
        }

        ElMessage.success("PDF生成成功")
        return response.data
      }

      ElMessage.error("PDF生成失败：响应数据为空")
      return null
    } catch (error) {
      console.error("生成简历PDF失败:", error)
      ElMessage.error("PDF生成失败，请稍后重试")
      return null
    } finally {
      loading.value = false
    }
  }

  return {
    // 状态
    loading,
    resumeList,
    total,
    currentDetail,
    queryParams,
    formData,
    cachedPdfInfo,

    // 方法
    fetchUserResumes,
    loadMore,
    fetchResumeDetail,
    createResume,
    updateResume,
    removeResume,
    updateQueryParams,
    resetQueryParams,
    resetCurrentDetail,
    initFormData,
    resetFormData,
    filterEmptyData,
    addSkill,
    removeSkill,
    addInternExperience,
    removeInternExperience,
    addLanguage,
    removeLanguage,
    addAward,
    removeAward,
    setCurrentUserId,
    generateResumePdf
  }
})

/**
 * @description 在 SPA 应用中可用于在 pinia 实例被激活前使用 store
 * @description 在 SSR 应用中可用于在 setup 外使用 store
 */
export function useResumeStoreOutside() {
  return useResumeStore(pinia)
}
